#include "mqtt_handler.h"
#include "config.h"
#include "page_manager.h"
#include <WiFiManager.h>

WiFiClient espClient;
PubSubClient client(espClient);

// 生成唯一的 Client ID
String generateClientId() {
  String clientId = "ESP32-";
  clientId += String(WiFi.macAddress());
  return clientId;
}

void initMQTT() {
    // WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    // while (WiFi.status() != WL_CONNECTED) {
    //     delay(1000);
    //     Serial.println("Connecting to WiFi...");
    // }
    // Serial.println("Connected to WiFi");
    initWificonfig();


    String clientId = generateClientId();

    client.setServer(MQTT_SERVER, MQTT_PORT);
    client.setCallback(callback);
    while (!client.connected()) {
        Serial.println("Connecting to MQTT...");
        if (client.connect(clientId.c_str())) {
            Serial.println("Connected to MQTT");
            client.subscribe(MQTT_TOPIC);
        } else {
            Serial.print("Failed with state ");
            Serial.print(client.state());
            delay(2000);
        }
    }
}

void initWificonfig()
{
    // 创建WiFiManager对象
    WiFiManager wifiManager;

    // 清除已保存的WiFi配置（可选，仅在需要重置时取消注释）
    //wifiManager.resetSettings();

    // 配置WiFiManager
    wifiManager.setDebugOutput(true);  // 启用调试输出
    wifiManager.setConnectTimeout(60); // 设置连接超时时间为180秒
    wifiManager.setConfigPortalTimeout(60); // 配置门户超时时间为180秒
    wifiManager.setMinimumSignalQuality(30); // 设置最小信号质量（30%）
    //wifiManager.setAPStaticIPConfig(IPAddress(192,168,4,1), IPAddress(192,168,4,1), IPAddress(255,255,255,0)); // 设置AP模式的IP
    
    // 设置AP模式的SSID和密码
    String apName = "AIScreen_" + String((uint32_t)ESP.getEfuseMac(), HEX);
    
    // 自动连接到先前保存的网络
    // 如果连接失败，它将启动接入点
    Serial.println("正在尝试连接WiFi...");
    if (!wifiManager.autoConnect(apName.c_str(), "12345678")) {
        Serial.println("无法连接WiFi，将在3秒后重启...");
        delay(3000);
        ESP.restart();
    }

    // 成功连接到WiFi
    Serial.println("已成功连接到WiFi");
    Serial.print("IP地址: ");
    Serial.println(WiFi.localIP());
    Serial.print("WiFi SSID: ");
    Serial.println(WiFi.SSID());
    Serial.print("信号强度: ");
    Serial.println(WiFi.RSSI());
}

// 添加重连函数
bool reconnect() {
    String clientId = generateClientId();
    Serial.println("Attempting MQTT connection...");
    
    // 尝试连接
    if (client.connect(clientId.c_str())) {
        Serial.println("Connected to MQTT");
        // 重新订阅主题
        client.subscribe(MQTT_TOPIC);
        return true;
    } else {
        Serial.print("Failed to connect, rc=");
        Serial.print(client.state());
        return false;
    }
}

void handleMQTT() {
    if (!client.connected()) {
        long now = millis();
        static long lastReconnectAttempt = 0;
        if (now - lastReconnectAttempt > 1000) {  // 每1秒尝试重连一次
            lastReconnectAttempt = now;
            if (reconnect()) {
                lastReconnectAttempt = 0;
            }
        }
    } else {
        client.loop();
    }
}

void callback(char* topic, byte* payload, unsigned int length) {
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    
    if (length == 0) {
        Serial.println("Empty message received");
        return;
    }
    
    String message = "";
    for (int i = 0; i < length; i++) {
        message += (char)payload[i];
    }
    Serial.println(message);

    // 添加消息格式验证
    if (message.length() == 0) {
        Serial.println("Invalid message format");
        return;
    }

    int pageType = 0;
    int duration = 0;

    int index = message.indexOf(',');
    if (index != -1) {
        // 有duration参数
        String pageTypeStr = message.substring(0, index);
        String durationStr = message.substring(index + 1);
        
        pageType = pageTypeStr.toInt();
        duration = durationStr.toInt();
    } else {
        // 只有pageType参数
        pageType = message.toInt();
    }

    // 验证pageType是否有效
    if (pageType <= 0) {
        Serial.println("Invalid page type");
        return;
    }

    currentPage.type = pageType;
    currentPage.isTemporary = (duration > 0);
    currentPage.displayDuration = duration;
    currentPage.startTime = millis();

    displayPage(pageType);
}    